package com.yang.booking.config;

import com.yang.booking.pojo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.util.Date;

@Configuration
public class JwtTokenConfig {

    private static final Logger logger = LoggerFactory.getLogger(JwtTokenConfig.class);
    /** 秘钥 */
    @Value("${jwt.secret}")
    private String secret;
    /** 过期时间(秒) */
    @Value("${jwt.expire}")
    private long expire;

    @Value("Authorization")
    private String header;

    /**
     * 生成jwt token
     */
    public String generateToken(User u) {
        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + expire * 1000);
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")

                .setSubject(u.getUsername() + " " + u.getPassword() + " && ")
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)

                .claim("id", u.getId())
                .claim("password", u.getPassword())
                .claim("name", u.getUsername())

                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    //解析并验证token
    public Claims getClaimByToken(String token) {
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        }catch (Exception e){
            logger.debug("validate is token error ", e);
            return null;
        }
    }

    /**
     * token是否过期
     * @return true：过期
     */
    public static boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }

    /**
     * 获取token失效时间
     * @param token
     * @return
     */
    public Date getExpirationDateFromToken(String token) {
        return getClaimByToken(token).getExpiration();
    }
    /**
     * 获取用户名从token中
     */
    public String getUsernameFromToken(String token) {
        return getClaimByToken(token).getSubject();
    }

    /**
     * 获取jwt发布时间
     */
    public Date getIssuedAtDateFromToken(String token) {
        return getClaimByToken(token).getIssuedAt();
    }

    // --------------------- getter & setter ---------------------

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    public long getExpire() {
        return expire;
    }

    public void setExpire(long expire) {
        this.expire = expire;
    }

    public String getHeader() {
        return header;
    }

    public void setHeader(String header) {
        this.header = header;
    }

}
